package ink.feta.task.controller;


import ink.feta.task.service.ElasticJobService;
import org.apache.shardingsphere.elasticjob.api.JobConfiguration;
import org.apache.shardingsphere.elasticjob.lite.lifecycle.domain.JobBriefInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/job")
public class JobController {

    @Autowired
    ElasticJobService elasticJobService;

    @RequestMapping(path = "/create")
    public JobConfiguration createJob() {
        JobConfiguration configuration
                = JobConfiguration.newBuilder("myElasticJob", 3)
                .cron("0/30 * * * * ?")
                .jobListenerTypes("simpleJobListener", "distributeOnceJobListener")
                .shardingItemParameters("0=Beijing,1=Shanghai,2=Guangzhou")
                .build();
        elasticJobService.createJob(configuration);
        return configuration;
    }

    @RequestMapping(path = "pause")
    public String pauseJob(String jobName) {
        return elasticJobService.pauseJob("myElasticJob");
    }

    @RequestMapping(path = "resume")
    public String resumeJob(String jobName) {
        return elasticJobService.resumeJob("myElasticJob");
    }

    @RequestMapping(path = "delete")
    public String delete(String jobName) {
        return elasticJobService.deleteJob("myElasticJob");
    }

    @RequestMapping(path = "update")
    public JobConfiguration update(String jobName) {
        JobConfiguration configuration
                = JobConfiguration.newBuilder("myElasticJob", 3)
                .cron("0/5 * * * * ?")
                .jobListenerTypes("simpleJobListener", "distributeOnceJobListener")
                .shardingItemParameters("0=Beijing,1=Shanghai,2=Guangzhou")
                .build();
        return elasticJobService.updateJob("myElasticJob", configuration);
    }

    @RequestMapping(path = "list")
    public Collection<JobBriefInfo> list() {
        return elasticJobService.listJobs();
    }
}
